﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Store.Web.Services;
using System.Web.Configuration;
using Store.Web.Models;

namespace Store.Web.Controllers
{
    public class ProductController : Controller
    {
        private readonly ProductService _productService;
        public ProductController()
        {
            string connectionString = WebConfigurationManager.ConnectionStrings["StoreDb"].ConnectionString;
            _productService = new ProductService(connectionString);
        }

        public ActionResult Index()
        {
            var products = _productService.GetProducts();
            return View(products);
        }

        public ActionResult Edit(int id)
        {
            var product = _productService.GetProduct(id);
            return View(product);
        }

        [HttpPost]
        public ActionResult Edit(Product product)
        {
            if (ModelState.IsValid)
            {
                _productService.UpdateProduct(product);
                return View("Index", _productService.GetProducts());
            }

            return View(product);
        }

        public ActionResult Details(int id)
        {
            var product = _productService.GetProduct(id);
            return View(product);
        }

        public ActionResult Create()
        {
            return View(new Product());
        }

        [HttpPost]
        public ActionResult Create(Product product)
        {
            if (ModelState.IsValid)
            {
                _productService.AddProduct(product);
                return View("Index", _productService.GetProducts());
            }

            return View(product);
        }
    }
}
